package com.sp.business.normalization.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;

import com.sp.generated.xml.firemon.RoutingInstance;
import com.sp.generated.xml.firemon.RoutingInstanceCollection;

public class RoutingInstanceKeyGenerator
{
  private static final org.slf4j.Logger logger = LoggerFactory.getLogger(RoutingInstanceKeyGenerator.class);
  
  public static void generateRoutingInstanceKeys(final RoutingInstanceCollection previous, final RoutingInstanceCollection current)
  {
    final Map<String, RoutingInstance> previousMap = new HashMap<String, RoutingInstance>();

    if (previous != null)
    {
      for (final RoutingInstance ri : previous.getRoutingInstances())
      {
        String guid = ri.getUID();
        if (StringUtils.isBlank(guid) || !NormalizationUtil.isStringUUID(guid))
        {
          guid = String.format("{%s}", UUID.randomUUID().toString().toUpperCase());
          ri.setUID(guid);
          ri.setXsid("RoutingInstance" + guid.replaceAll("\\{", "").replaceAll("\\}", ""));
        }
        
        
        previousMap.put(mapKeyFor(ri), ri);
      }
    }

    if (current != null)
    {
      for (final RoutingInstance ri : current.getRoutingInstances())
      {
        final String key = mapKeyFor(ri);
        final RoutingInstance previousMatch = previousMap.remove(key);
        copyUID(previousMatch, ri);
      }
    }

  }

  protected static String copyUID(RoutingInstance previous, RoutingInstance current)
  {
    String guid = null;

    if (previous != null)
    {
      guid = previous.getUID();
    }

    if (StringUtils.isBlank(guid) || !NormalizationUtil.isStringUUID(guid))
    {
      guid = String.format("{%s}", UUID.randomUUID().toString().toUpperCase());
    }

    current.setUID(guid);

    current.setXsid("Route" + guid.replaceAll("\\{", "").replaceAll("\\}", ""));

    return guid;
  }
  
  protected static String mapKeyFor(RoutingInstance ri)
  {
    //key = name + instanceType
    String type = (ri.getInstanceType() == null ) ? "" : ri.getInstanceType().getValue();
    if(ri.getName()==null)
    {
      logger.error("Routing instance missing required name");
      if(ri.getXsid()!=null)
      {
        logger.error("Routing instance missing required name but has xsid " + ri.getXsid());
      }
    }
    String name = (ri.getName()==null) ? "" : ri.getName().getValue();
    String key = name + type;
    return key;
  }
 
}